from django.conf import settings
from fdfs_client.client import Fdfs_client
from celery_tasks.static_file.tasks import get_detail_html

from goods.models import  SKUImage,SKU
from rest_framework import serializers


class ImageSerialier(serializers.ModelSerializer):
    # 返回图片关联的sku的id值
    sku= serializers.PrimaryKeyRelatedField(read_only=True)
    # sku_id=serializers.IntegerField()
    class Meta:
        model=SKUImage
        fields=('sku','image','id')
    def create(self, validated_data):
        '''新增图片信息'''
        # 建立fastdfs客户端连接
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 获取图片
        request=self.context['request']
        image_file = request.FILES.get('image')
        # 上传图片
        res = client.upload_by_buffer(image_file.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError({'error':'图片上传失败'})
        # 获取sku_id
        sku_id = request.data.get('sku')
        # 获取dfs上传之后的图片地址
        image_url = res['Remote file_id']
        img = SKUImage.objects.create(sku_id=sku_id, image=image_url)
        # 异步生成静态页面
        get_detail_html.delay(img.sku.id)
        return img


    def update(self, instance, validated_data):
        '''更新图片信息'''
        # 建立fastdfs客户端连接
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 获取图片
        request = self.context['request']
        image_file = request.FILES.get('image')
        # 上传图片
        res = client.upload_by_buffer(image_file.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError({'error': '图片上传失败'})
        instance.image=res['Remote file_id']
        instance.save()
        # 异步生成静态页面
        get_detail_html.delay(instance.sku.id)
        return instance



class SKUSeriazlier(serializers.ModelSerializer):
    '''获取新增图片时的SKU商品信息'''
    class Meta:
        model=SKU
        fields=('id','name')